from flask import Flask
import logging
from config import logger

# 导入组件
from camera import CameraManager
from robot_controller import RobotController
from joystick import JoystickManager
from api_routes import ApiRoutes
from web_routes import WebRoutes

def create_app():
    """创建Flask应用"""
    app = Flask(__name__)
    
    # 初始化组件
    robot_controller = RobotController()

    # 初始化其他组件
    camera_manager = CameraManager()
    joystick_manager = JoystickManager(robot_controller)
    api_routes = ApiRoutes(app, joystick_manager, robot_controller, camera_manager)
    web_routes = WebRoutes(app, joystick_manager)

    return app

if __name__ == '__main__':
    app = create_app()
    
    # 获取机器人控制器实例
    robot_controller = None
    for rule in app.url_map.iter_rules():
        if hasattr(app.view_functions[rule.endpoint], 'robot_controller'):
            robot_controller = app.view_functions[rule.endpoint].robot_controller
            break
    
    # 自动启动机器人控制（如果可用）
    if robot_controller and robot_controller.is_available():
        logger.info("自动启动机器人控制线程")
        robot_controller.start_control()
    
    # 启动Flask应用
    app.run(host='0.0.0.0', port=5000, debug=True)
